<?php

namespace bc\model\api;

use bc\ar\MActiveRecord;
use bc\model\ecs\UserModel;
use bc\model\wx\report\CodeModel;
use frontend\models\User;
use bc\util\Util;

class AppTokenModel extends MActiveRecord
{
	
	public $autoId = 'token_id';
	
	public static function tableName()
	{
		return '{{%app_token}}';
	}

	//添加数据
	public function addToken($ecsuserD){
		$tokenData = array();
		$token = Util::create_guid(32,$ecsuserD['user_id']);
		$time = time();
		$tokenData = array(
			'token_id'=>$token,
			'ip_address'=>'',
			'user_data'=>json_encode($ecsuserD),
			'last_fresh_time'=>$time,
			'create_time'=>$time,
			'expiration_time'=>$time+86400*15,
			'update_time'=>$time,
			'user_id'=>$ecsuserD['user_id']
		);

		if(!$this->add($tokenData))
			Util::echoJosnpData(1,array(),'数据库错误');
		return $token;
	}

	//更新数据
	public function updToken($ecsuserD){
		$tokenData = array();
		$token = Util::create_guid(32,$ecsuserD['user_id']);
		$time = time();
		$tokenData = array(
			'token_id'=>$token,
			'ip_address'=>'',
			'user_data'=>json_encode($ecsuserD),
			'last_fresh_time'=>$time,
			'expiration_time'=>$time+86400*15,
			'update_time'=>$time
		);

		if(!$this->updateAll($tokenData,['user_id'=>$ecsuserD['user_id']]))
			Util::echoJosnpData(1,array(),'数据库错误');
		return $token;
	}

	//获取用户信息
	public function getToken($ecsuserD){
		$data=$this->getRow(['user_id'=>$ecsuserD['user_id']]);
		if($data){
			//更新token
			$tokendata=$this->updToken($ecsuserD);
			return $tokendata;
		}

		//获取用户数据
		$dao = new MActiveRecord();
		return $this->addToken($ecsuserD);
	}

	/**
	 * 登陆手机号/code检查
	 */
	public function checklogin($mobile,$code,$code_id){
		$password = trim($code);
		$mobile = trim($mobile);
		if($mobile == '' || $password == ''){
			return false;
		}

		if(!preg_match("/^1[34578]\d{9}$/", $mobile)){
			return false;
		}

		//检测code
		$codeM = new CodeModel();
		$codeD = $codeM->getRow(['id'=>$code_id]);
		($codeD['code']==$code && $codeD['mobile']==$mobile)?'':Util::echoJosnpData(1,array(),'验证码不正确');
		($codeD['create_time'] + 120 >time())?'':Util::echoJosnpData(1,array(),'验证码失效');
		$ecsuserM = new UserModel();
		$ecsuserD = $ecsuserM -> getRow(['mobile'=>$mobile]);
		!empty($ecsuserD)?'':Util::echoJosnpData(1,array(),'请先关注"芝士妈妈在线"公众号');
		return $this->getToken($ecsuserD);
	}

	/**
	 * 登陆手机号/code检查
	 */
	public function checkToken($token){
		$token = trim($token);
		if($token == ''){
			return false;
		}

		$data=$this->getRow(['token_id'=>$token]);
		if(empty($data)){
			return false;
		}else{
			if($data['expiration_time']<=time())
			{
				return false;
			}
			return $data['token_id'];
		}
	}
}

